#!/bin/bash
set -e
set -u

TestName="$(basename "$(pwd)")"
export TestName

JobName=backup-susan-fd

#shellcheck source=../environment.in
. ./environment

#shellcheck source=../scripts/functions
. "${rscripts}"/functions
"${rscripts}"/cleanup
"${rscripts}"/setup

exit_with_error() {
  echo "$1"
  estat=1
  end_test
  exit 1
}

stop_susan_daemons() {
  stop_susan
}

# Directory to backup.
# This directory will be created by setup_data().
BackupDirectory="${tmp}/data"

# Use a tgz to setup data to be backed up.
# Data will be placed at "${tmp}/data/".
setup_data "$@"

start_test

stop_susan_daemons

cat <<END_OF_DATA >"${tmp}"/bconcmds
@$out /dev/null
messages
@$out $tmp/log1.out
setdebug level=100 storage=File
label volume=TestVolume001 storage=File pool=Full
run job=$JobName yes
status director
status client
status storage=File
wait
messages
@#
@# now do a restore
@#
@$out $tmp/log2.out
wait
restore client=susan-fd fileset=SelfTest where=$tmp/susan-restores select all done
yes
wait
messages
quit
END_OF_DATA

"${rscripts}"/susan-ctl-dir start
sleep 1

echo "Waiting for the director to start"
if ! echo "status dir" | "${SUSAN_BCONSOLE_BINARY}" -c "$conf"/bconsole.conf > /dev/null 2>&1; then
  exit_with_error "Director did not start"
fi
echo "Director is running"

"${rscripts}"/susan-ctl-sd start
"${rscripts}"/susan-ctl-fd start

echo "Check if the filedaemon is connected to the director"
i=0
until echo "status dir" | \
  "${SUSAN_BCONSOLE_BINARY}" -c "$conf"/bconsole.conf | \
  grep --quiet --word-regexp "${TestName}-fd"; do
  echo "waiting for client to connect (#$i)... "
  ((i=i+1))
  sleep 1
  if [ $i -gt 60 ]; then
    exit_with_error "Filedaemon ${TestName} could not connect to director"
  fi
done

echo "Filedaemon is connected, running backup and restore"

run_bconsole "$tmp/bconcmds"

check_for_zombie_jobs storage=File

"${rscripts}"/susan-ctl-dir stop
"${rscripts}"/susan-ctl-sd stop
"${rscripts}"/susan-ctl-fd stop

check_two_logs
check_restore_diff "${BackupDirectory}"
end_test

